<?php

namespace app\adminapi\controller;

use app\model\PlatformConfigModel;
use Respect\Validation\Exceptions\ValidationException;
use Respect\Validation\Validator as v;
use Webman\Http\Request;

class PlatformConfig extends BaseAdminApi
{
    protected $dataModel = PlatformConfigModel::class;
    protected array $allowSearch = ['name', 'key'];

    /**
     * 获取配置
     */
    public function getPlatformConfig(Request $request)
    {
        try {
            $params = v::input($request->get(), [
                'key' => v::optional(v::stringType()->notEmpty())->setName('配置键'),
            ]);
        } catch (ValidationException $e) {
            return $this->fail($e->getMessage());
        }

        $configKey = $params['key'] ?? null;

        if (!empty($configKey)) {
            // 获取指定配置
            $config = PlatformConfigModel::where('key', $configKey)
                ->first();
            
            if (!$config) {
                return $this->fail('配置不存在');
            }
            
            return $this->success($config);
        } else {
            // 获取所有配置
            $configs = PlatformConfigModel::getAllConfigs();
            return $this->success($configs);
        }
    }

    /**
     * 保存平台配置
     */
    public function saveConfig(Request $request)
    {
        $params = $request->post();

        try {

            $existConfig = PlatformConfigModel::where('key', $params['key'])->first();

            // 更新现有配置
            $existConfig->update([
                'name' => $params['name'],
                'value' => $params['value']
            ]);

            return $this->success("配置更新成功");
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }
}